/**
 * 生成视频组件
 */
const GenerateVideoView = {
    name: 'GenerateVideoView',
    props: {
        settings: {
            type: Object,
            default: () => ({
                model: 'cogvideox-flash',
                quality: 'quality',
                with_audio: true,
                size: '1920x1080',
                fps: 30
            })
        }
    },
    data() {
        return {
            inputText: '',
            videoData: null,
            loading: false,
            error: null
        };
    },
    methods: {
        async submit() {
            if (!this.inputText.trim()) {
                this.error = '请输入视频描述';
                return;
            }
            
            this.loading = true;
            this.error = null;
            this.videoData = null;
            
            try {
                // 创建视频生成任务
                const result = await apiClient.generateVideo(this.inputText.trim(), null, this.settings);
                
                if (result.success) {
                    const taskId = result.data.task_id;
                    
                    // 任务处理中状态
                    this.videoData = {
                        type: 'video_task',
                        task_id: taskId,
                        status: 'processing',
                        message: '视频生成中，请稍候...'
                    };
                    
                    // 清空输入框
                    this.inputText = '';
                    
                    // 轮询任务状态
                    this.pollTaskStatus(taskId);
                } else {
                    this.error = result.error || '生成视频失败';
                    this.loading = false;
                }
            } catch (error) {
                console.error('生成视频失败:', error);
                const errorInfo = window.ErrorHandler ? window.ErrorHandler.formatError(error) : { message: error.message || '未知错误' };
                this.error = errorInfo.message;
                if (errorInfo.suggestion) {
                    this.$message.warning(errorInfo.suggestion);
                }
                this.loading = false;
            }
        },
        async pollTaskStatus(taskId) {
            try {
                await apiClient.pollTaskStatus(
                    taskId,
                    (status, result) => {
                        // 状态更新回调
                        if (status === 'processing') {
                            this.videoData = {
                                type: 'video_task',
                                task_id: taskId,
                                status: 'processing',
                                message: '视频生成中，请稍候...'
                            };
                        } else if (status === 'completed') {
                            // 任务完成
                            const videoUrl = result?.video_url || result?.video_result?.[0]?.url;
                            const coverUrl = result?.cover_image_url || result?.video_result?.[0]?.cover_image_url;
                            
                            this.videoData = {
                                type: 'video',
                                task_id: taskId,
                                status: 'completed',
                                result: {
                                    video_url: videoUrl,
                                    cover_image_url: coverUrl
                                },
                                message: '视频生成成功！'
                            };
                            this.loading = false;
                            this.$message.success('视频生成成功！');
                        } else if (status === 'failed') {
                            this.error = '视频生成失败';
                            this.loading = false;
                        }
                    },
                    30, // 最多查询30次
                    3000 // 每3秒查询一次
                );
            } catch (error) {
                console.error('轮询任务状态失败:', error);
                this.error = '查询任务状态失败：' + (error.message || '未知错误');
                this.loading = false;
            }
        },
        downloadVideo() {
            if (!this.videoData || !this.videoData.result || !this.videoData.result.video_url) return;
            
            const videoUrl = this.videoData.result.video_url;
            fetch(videoUrl)
                .then(response => response.blob())
                .then(blob => {
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `generated-video-${Date.now()}.mp4`;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                })
                .catch(err => {
                    console.error('下载失败:', err);
                    alert('视频下载失败，请右键视频另存为');
                });
        }
    },
    template: `
        <el-card shadow="hover" style="margin: 20px;">
            <div slot="header">
                <span style="font-size: 18px; font-weight: 600;">生成视频</span>
                <p style="margin: 8px 0 0 0; color: #909399; font-size: 14px;">输入视频描述，AI将为您生成视频</p>
            </div>
            
            <el-input
                v-model="inputText"
                type="textarea"
                :rows="4"
                placeholder="请输入视频描述，例如：海浪拍打着沙滩"
            ></el-input>
            
            <div style="margin-top: 20px;">
                <el-button 
                    type="primary" 
                    @click="submit"
                    :loading="loading"
                    :disabled="!inputText.trim()"
                    icon="el-icon-video-camera"
                    style="width: 100%;"
                >
                    {{ loading ? '任务创建中...' : '生成视频' }}
                </el-button>
            </div>

            <!-- 错误提示 -->
            <el-alert
                v-if="error"
                :title="error"
                type="error"
                :closable="true"
                @close="error = null"
                show-icon
                style="margin-top: 20px;"
            ></el-alert>

            <div v-if="videoData && videoData.status === 'processing'" style="margin-top: 20px;">
                <el-alert
                    title="视频正在生成中，请稍候..."
                    type="info"
                    :closable="false"
                    show-icon
                ></el-alert>
            </div>

            <div v-if="videoData && videoData.status === 'completed' && videoData.result && videoData.result.video_url" style="margin-top: 20px;">
                <el-card shadow="never">
                    <div slot="header" style="display: flex; justify-content: space-between; align-items: center;">
                        <h3 style="margin: 0; font-size: 16px; font-weight: bold;">生成结果</h3>
                        <el-button 
                            type="primary" 
                            size="small" 
                            icon="el-icon-download"
                            @click="downloadVideo"
                        >
                            下载视频
                        </el-button>
                    </div>
                    <video :src="videoData.result.video_url" controls style="width: 100%; border-radius: 4px;"></video>
                </el-card>
            </div>
        </el-card>
    `
};

